package com.finna.tenant.controller;

import com.finna.common.utils.ResponseResult;
import com.finna.tenant.dto.*;
import com.finna.tenant.dto.RoleDTO.RoleCreateRequest;
import com.finna.tenant.dto.RoleDTO.RoleListRequest;
import com.finna.tenant.dto.RoleDTO.RoleResponse;
import com.finna.tenant.dto.RoleDTO.RoleUpdateRequest;
import com.finna.tenant.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色控制器
 */
@RestController
@RequestMapping("/role")
@Tag(name = "角色接口", description = "角色信息相关接口")
public class RoleController {
    
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 创建角色
     */
    @PostMapping("/add")
    @Operation(summary = "创建角色", description = "创建新角色")
    public ResponseResult<RoleResponse> addRole(
            @Validated @RequestBody RoleCreateRequest request) {
        try {
            RoleResponse response = roleService.create(request);
            logger.info("创建角色成功: roleId={}", response.getId());
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("创建角色失败: {}", e.getMessage());
            return ResponseResult.error(400, "角色创建失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("创建角色失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改角色
     */
    @PutMapping("/{roleId}")
    @Operation(summary = "修改角色", description = "修改角色信息")
    public ResponseResult<RoleResponse> modifyRole(
            @Parameter(description = "角色ID") @PathVariable Long roleId,
            @RequestBody RoleUpdateRequest request) {
        try {
            RoleResponse response = roleService.update(roleId, request);
            logger.info("修改角色成功: roleId={}", roleId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("修改角色失败: roleId={}, error={}", roleId, e.getMessage());
            return ResponseResult.error(404, e.getMessage());
        } catch (Exception e) {
            logger.error("修改角色失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色修改失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{roleId}")
    @Operation(summary = "删除角色", description = "删除角色（软删除）")
    public ResponseResult<Void> deleteRole(
            @Parameter(description = "角色ID") @PathVariable Long roleId) {
        try {
            roleService.delete(roleId);
            logger.info("删除角色成功: roleId={}", roleId);
            return ResponseResult.success(null);
        } catch (RuntimeException e) {
            logger.error("删除角色失败: roleId={}, error={}", roleId, e.getMessage());
            return ResponseResult.error(404, e.getMessage());
        } catch (Exception e) {
            logger.error("删除角色失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取角色详情
     */
    @GetMapping("/{roleId}")
    @Operation(summary = "获取角色详情", description = "根据ID获取角色详细信息")
    public ResponseResult<RoleResponse> roleDetail(
            @Parameter(description = "角色ID") @PathVariable Long roleId) {
        try {
            RoleResponse response = roleService.getById(roleId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("查询角色失败: roleId={}, error={}", roleId, e.getMessage());
            return ResponseResult.error(404, "角色不存在");
        } catch (Exception e) {
            logger.error("查询角色失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有角色（不分页）
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有角色", description = "获取所有角色列表（不分页）")
    public ResponseResult<List<RoleResponse>> allRoles() {
        try {
            List<RoleResponse> responses = roleService.getAll();
            logger.info("查询所有角色成功: count={}", responses.size());
            return ResponseResult.success(responses);
        } catch (Exception e) {
            logger.error("查询所有角色失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取角色列表（分页）
     */
    @GetMapping("/page")
    @Operation(summary = "获取角色列表", description = "分页查询角色列表，支持过滤条件，自动排除超级管理员角色")
    public ResponseResult<PageResponse<RoleResponse>> roleList(
            @Parameter(description = "角色名称") @RequestParam(required = false) String name,
            @Parameter(description = "状态") @RequestParam(required = false) Boolean status,
            @Parameter(description = "页码") @RequestParam(required = false, defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            RoleListRequest request = new RoleListRequest();
            request.setName(name);
            request.setStatus(status);
            request.setPage(page);
            request.setPageSize(pageSize);
            
            PageResponse<RoleResponse> response = roleService.list(request);
            logger.info("角色列表查询成功: page={}, pageSize={}, total={}", page, pageSize, response.getTotal());
            
            return ResponseResult.success(response);
        } catch (Exception e) {
            logger.error("角色列表查询失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "角色列表查询失败: " + e.getMessage());
        }
    }
}

